/*
 * Copyright (C) 2009 CodeWerkz
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.codewerkz.prompty;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.codewerkz.util.Utils;

/**
 * Database Adapter for the Presentation Table. CRUD Operations.
 * 
 * @author ChaZ
 */
public class PresentationsDbAdapter {

	// Database columns.
    public static final String KEY_NAME = "name";
    public static final String KEY_DESC = "description";
    public static final String KEY_ROWID = "_id";
    public static final String KEY_DELAYS = "delays";
    
    // Other database related variables.
    private static final String TAG = "PresentationsDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    
    // Database creation SQL Variables.
    private static final String DATABASE_CREATE =
            "CREATE TABLE presentation (_id integer primary key autoincrement, "
                    + "name text not null, description text not null, delays integer not null);";
    private static final String DATABASE_CREATE2 =
    		"CREATE TABLE slides (_id integer primary key autoincrement, "
        	+ "p_id integer not null, title text not null, prompt text not null, time integer);";
    
    // Database options (name, table, etc)
    private static final String DATABASE_NAME = "prompty";
    private static final String DATABASE_TABLE = "presentation";
    private static final int DATABASE_VERSION = 3;

    private final Context mCtx;
    
    /**
     * Database helper class.
     */
    private static class DatabaseHelper extends SQLiteOpenHelper {

    	/**
    	 * Constructor
    	 * 
    	 * @param context Context within it is running in.
    	 */
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        /**
         * Runs when the database object is created.
         * 
         * @param db SQLiteDatabase
         * @return void
         */
        @Override
        public void onCreate(SQLiteDatabase db) {
        	Log.w(TAG, "Creating database");
            db.execSQL(DATABASE_CREATE);
            db.execSQL(DATABASE_CREATE2);
        }
       
        /**
         * Runs when the database object is upgraded.
         * 
         * @param db SQLiteDatabase
         * @param oldVersion Integer for old version of Database
         * @param newVersion Integer for new version of Database
         */
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS presentation");
            db.execSQL("DROP TABLE IF EXISTS slides");
            onCreate(db);
        }
    }

    /**
     * @param ctx Context of which it is running.
     */
    public PresentationsDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Constructor overload: Open the presentation database. If it cannot be 
     * opened, try to create a new instance of the database. If it cannot be 
     * created, throw an exception to signal failure.
     * 
     * @throws SQLiteException
     */
    public PresentationsDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }
    
    /**
     * Closes the database connection.
     */
    public void close() {
    	Log.v(TAG, "Closing database..");
        mDbHelper.close();
    }
    
    /**
     * Create a new presentation using the title and body provided. If the
     * presentation is successfully created return the new rowId for that pres, 
     * otherwise return a -1 to indicate failure. 
     */
    public long createPresentation(String name, String desc, boolean delays) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_NAME, name);
        initialValues.put(KEY_DESC, desc);
        initialValues.put(KEY_DELAYS, Utils.boolToInt(delays));
        return mDb.insert(DATABASE_TABLE, null, initialValues);
    }

    /**
     * Delete the presentation with the given rowId
     * 
     * @param rowId Id of row to delete.
     * @return boolean Returns true if deleted successfully.
     */
    public boolean deletePresentation(long rowId) {
        return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }
        
    /**
     * Return a Cursor over the list of all presentations in the database
     * 
     * @return Cursor Cursor over the list of all presentations in the database 
     */
    public Cursor fetchAllPresentations() {
        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
                KEY_DESC}, null, null, null, null, null);
    }
      
    /**
     * Return a Cursor positioned at the presentation that matches the given rowId
     * 
     * @param rowId Id of row to find.
     * @return Cursor Cursor to the presentation.
     */
    public Cursor fetchPresentation(long rowId) throws SQLException {

        Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
        			KEY_NAME, KEY_DESC, KEY_DELAYS}, KEY_ROWID + "=" + rowId, null,
                    null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }

    /**
     * Gets the delay colum from the presentation.
     * 
     * @param rowId Row Id of the presentation.
     * @return Cursor to the row and column.
     */
    public Cursor fetchDelayInformation (long rowId) throws SQLException {
    	
    	Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {KEY_DELAYS}, KEY_ROWID + "=" + rowId, null,
    			null, null, null, null);
    	
    	if(mCursor != null) {
    		mCursor.moveToFirst();
    	}
    	return mCursor;
    	
    }

    /**
     * Update the presentation using the details provided. The presentation to 
     * be updated is specified using the rowId, and it is altered to use the 
     * values passed in
     * 
     * @param rowId Id of presentation.
     * @param name Name of presentation.
     * @param desc Description of Presentation.
     * @param delays Boolean whether to enable delays or not.
     * @return boolean Returns true if successful
     */
    public boolean updatePresentation(long rowId, String name, String desc, boolean delays) {
        ContentValues args = new ContentValues();
        args.put(KEY_NAME, name);
        args.put(KEY_DESC, desc);
        args.put(KEY_DELAYS, Utils.boolToInt(delays));
        return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
}
